package com.tarena.csmall.sentinel.demo01.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.tarena.csmall.sentinel.demo01.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author java@tedu.cn
 * @version 1.0
 */
@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;
    @GetMapping("/hello")
    public String sayHi(String name){
        //准备资源的入口 entry
        Entry entry=null;
        try{
            //对资源赋值,定义资源的名字
            entry= SphU.entry("sayHi");
            String result=helloService.sayHi(name);
            return result;
        }catch(FlowException e){
            //捕获异常之后,编写降级的逻辑
            return "对不起,您的请求,被流控了";
        }catch (BlockException e){
            //捕获异常之后,编写降级的逻辑
            return "对不起,您的请求,被blocked";
        }finally {
            //释放资源
            if (entry!=null){
                entry.exit();
            }
        }
    }
}
